<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>财政支付查询系统</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <link rel="stylesheet" href="<%=path%>/static/layui/css/layui.css"/>
    <script src="<%=path%>/static/iconfont/iconfont.js"></script>
    <script type="text/javascript" src="<%=path%>/static/jquery/jquery-3.1.0.js"></script>
    <script type="text/javascript" src="<%=path%>/static/layui/layui.js"></script>
    <script src="<%=path%>/static/echarts/echarts.js"></script>
    <style>
        body {
            background-color: #E6EAF0;
        }
        .header {
            position: fixed;
            padding-top: 30px;
            padding-left: 80px;
            padding-right: 80px;
            padding-bottom: 30px;
            width: calc(100% - 160px);
            height: 75px;
            z-index: 1000;
            background-color: #FFFFFF;
        }

        .content {
            /*padding-top: 135px;*/
            overflow-y: auto;
            padding-left: 80px;
            width: calc(100% - 160px);
            overflow: hidden;
        }
        .card {
            background-color: #FFFFFF;
            border-radius: 10px;
            padding: 15px;
        }
        .card-title {
            margin-top: 5px;
            margin-left: 16px;
            font-size: 16px;
            font-weight: bolder;
        }
        .card-num {
            margin-top: 20px;
            margin-left: 16px;
        }
        .card-number {
            font-size: 36px;
            font-weight: bolder;
            color: #42484d;
        }
        .card-amt {
            margin-top: 20px;
            margin-left: 16px;
        }
        .card-amount {
            font-size: 16px;
            font-weight: bolder;
            color: #004788;
        }
        .card-icon {
            line-height: 132px;
            text-align: center;
            font-size: 50px;
        }
        .icon {
            width: 1em;
            height: 1em;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
        .detail-card {
            border-radius: 10px;
            background-color: #FFFFFF;
            padding: 30px;
        }
        .detail-title {
            font-size: 16px;
            line-height: 40px;
            font-weight: bolder;
            color: #004788;
            text-align: center;
        }
        .detail-number {
            font-size: 18px;
            font-weight: bolder;
            text-align: center;
            color: #42484d;
        }
        .detail-amount {
            font-size: 18px;
            font-weight: bolder;
            text-align: left;
            color: #42484d;
        }
        .chart-card {
            border-radius: 10px;
            background-color: #FFFFFF;
            padding: 30px;
        }
        #chart {
            height: 500px;
        }
        .layui-form-label {
            width: 120px;
        }
        .layui-input-block {
            margin-left: 150px;
        }
        th div {
            text-align: center;
        }
        .layui-btn {
            background-color: #16b777;
        }
        .layui-btn-danger {
            background-color: #ff5722;
        }
        .layui-laypage .layui-laypage-curr .layui-laypage-em {
            background-color: #16b777;
        }
        .layui-col-seventh {
            width: 14.2857%;
            float: left;
            position: relative;
            display: block;
            box-sizing: border-box;
        }
        .detail-content {
            text-align: center;
            padding: 10px 5px;
        }

        .detail-combined {
            font-size: 16px;
            font-weight: bolder;
            color: #42484d;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 0 5px;
        }
        .zfdjlx-display {
            padding: 0 30px 0 10px;
            line-height: 38px;
            cursor: pointer;
            border: 1px solid #e6e6e6;
            position: relative;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .zfdjlx-text {
            display: inline-block;
            max-width: calc(100% - 20px);
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .button-container .layui-btn {
            white-space: nowrap;
            flex: 1;
        }

    </style>
</head>
<body>
<%--<div class="header">--%>
<%--    <div class="layui-row" style="margin-bottom: 30px;">--%>
<%--        <div class="layui-col-xs6">--%>
<%--            <img src="<%=path%>/static/image/logox.png"/>--%>
<%--        </div>--%>
<%--            <div class="layui-col-xs6">--%>
<%--                <div style="margin-top: 30px;font-size: 18px;text-align: right;font-weight: bolder;">--%>
<%--                    <span>当前在线：${loginUser.name}</span>&emsp;--%>
<%--                    <a href="JAVASCRIPT: exit_()" style="color: #004788;">退出</a>--%>
<%--                </div>--%>
<%--            </div>--%>
<%--    </div>--%>
<%--</div>--%>
<div class="content">
    <fieldset class="layui-elem-field layui-field-title" style="color: #1e9fff;">
        <legend>总盘支付看板</legend>
    </fieldset>
    <div class="layui-row layui-col-space20" id="summary-board">
        <!-- 总盘支付看板数据将在这里呈现 -->
    </div>
    <br/>
    <fieldset class="layui-elem-field layui-field-title" style="color: #1e9fff;">
        <legend>明细统计看板（当月）</legend>
    </fieldset>
    <div class="layui-row detail-card" id="details-board">
        <!-- 明细统计看板（当月）数据将在这里呈现 -->
    </div>
    <br/>
    <fieldset class="layui-elem-field layui-field-title" style="color: #1e9fff;">
        <legend>30天支付趋势</legend>
    </fieldset>
    <div class="layui-row chart-card">
        <div id="chart">
        <%--柱状图显示区域--%>
        </div>
    </div>

    <br/>
    <fieldset class="layui-elem-field layui-field-title" style="color: #1e9fff;">
        <legend>明细支付单</legend>
    </fieldset>
    <div class="chart-card">
        <div class="layui-row">
            <div class="layui-form">
                <form id="searchForm" class="layui-form" action="" lay-filter="searchForm">
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">支付单状态</label>
                            <div class="layui-input-block">
                                <select id="zfzt" name="zfzt">
                                    <option value="">全部</option>
                                    <option value="0">待支付</option>
                                    <option value="1">制单成功</option>
                                    <option value="2">制单失败</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">制单时间</label>
                            <div class="layui-input-block">
                                <input id="zdsj" type="text" name="zdsj" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>

                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">支付单类型</label>
                            <div class="layui-input-block">
                                <div class="layui-input zfdjlx-display" id="zfdjlxShow">
                                    <span class="zfdjlx-text" id="zfdjlxText">请选择支付单类型</span>
                                    <i class="layui-icon layui-icon-down" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%);"></i>
                                </div>
                                <input type="hidden" name="zfdjlx" id="zfdjlx">
                                <div id="zfdjlxContent" style="display: none; position: absolute; z-index: 9999; width: 100%; background: #fff; top: 100%; left: 0; margin-top: 5px;">
                                    <div style="padding: 10px; border: 1px solid #e6e6e6; border-radius: 2px; max-height: 300px; overflow-y: auto;">
                                        <div id="zfdjlxOptions">
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="一般支付申请" title="一般支付申请" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="财政支付申请" title="财政支付申请" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="政府采购申请无指标" title="政府采购申请无指标" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="零星采购申请" title="零星采购申请" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="公务卡申请" title="公务卡申请" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="支付申请" title="支付申请" lay-skin="primary"></div>
                                            <div style="margin: 5px 0;"><input type="checkbox" name="zfdjlxOptions" value="教育收费申请" title="教育收费申请" lay-skin="primary"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">原始单据类型</label>
                            <div class="layui-input-block">
                                <input id="djlxmc" type="text" name="djlxmc" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">原始单据编号</label>
                            <div class="layui-input-block">
                                <input id="djbh" type="text" name="djbh" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">支付金额</label>
                            <div class="layui-input-block">
                                <div style="display: flex; gap: 5%;">
                                    <input id="zfjeMin" type="text" name="zfjeMin" placeholder="最小金额" class="layui-input" style="flex: 1;">
                                    <span style="align-self: center; flex-shrink: 0;">-</span>
                                    <input id="zfjeMax" type="text" name="zfjeMax" placeholder="最大金额" class="layui-input" style="flex: 1;">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">摘要</label>
                            <div class="layui-input-block">
                                <input id="zy" type="text" name="zy" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">是否存疑</label>
                            <div class="layui-input-block">
                                <select id="doubt" name="doubt">
                                    <option value="">全部</option>
                                    <option value="0">否</option>
                                    <option value="1">是</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">收款人信息</label>
                            <div class="layui-input-block">
                                <input id="skr" type="text" name="skr" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">审核人</label>
                            <div class="layui-input-block">
                                <input id="auditor" type="text" name="auditor" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">模糊条件</label>
                            <div class="layui-input-block">
                                <input id="extra" type="text" name="extra" placeholder="请输入" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs3">
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn layui-bg-blue" onclick="search()" style="background-color: #004788 !important;">
                                    <i class="layui-icon layui-icon-search"></i>检索
                                </button>
                                <button type="button" class="layui-btn layui-btn-blue" onclick="resetForm()" style="background-color: #ec6337 !important;">
                                    <i class="layui-icon layui-icon-refresh"></i>重置
                                </button>
                            </div>
                        </div>
                    </div>

                </form>
            </div>
        </div>
        <div class="layui-form" id="table-list">
            <table class="layui-hide" id="dataTable" lay-filter="dataTable"></table>
        </div>
    </div>
</div>
<br/>
<br/>
<br/><br/>
<script>
    let form = layui.form;
    let table = layui.table;
    let layer = layui.layer;
    var laydate = layui.laydate;

    // 定义所有支付单类型
    const ALL_PAYMENT_TYPES = [
        '一般支付申请',
        '财政支付申请',
        '政府采购申请无指标',
        '零星采购申请',
        '公务卡申请',
        '支付申请',
        '教育收费申请'
    ];

    form.render();

    $(function() {
        // 获取看板数据
        $.get('<%=path%>/api/getDashboardData', function(res) {
            if (res.code === 200) {
                renderSummaryBoard(res.data.summary);
                renderDetailsBoard(res.data.details);
                initCharts(res.data.trend);
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
        });

        laydate.render({
            elem: '#zdsj',
            range: true
        });
        search();
        form.render();
    })

    // 渲染总盘支付看板
    function renderSummaryBoard(summary) {
        const summaryBoard = $('#summary-board');
        summaryBoard.empty();

        const cards = [
            { title: '当年总支付', number: summary.yearCount || 0, amount: summary.yearAmount || 0, icon: '#icon-dingdan' },
            { title: '当月总支付', number: summary.monthCount || 0, amount: summary.monthAmount || 0, icon: '#icon-pingtai' },
            { title: '待支付', number: summary.pendingCount || 0, amount: summary.pendingAmount || 0, icon: '#icon-xinyongkayinhangka' },
            { title: '当月制单成功', number: summary.successCount || 0, amount: summary.successAmount || 0, icon: '#icon-anquanyinsi' },
            { title: '当月制单失败', number: summary.failCount || 0, amount: summary.failAmount || 0, icon: '#icon-zhinengheyue' },
            { title: '当月制单存疑', number: summary.doubtCount || 0, amount: summary.doubtAmount || 0, icon: '#icon-quanlingyuguimo' }
        ];

        cards.forEach(function(card) {
            const formattedAmount = formatNumber(card.amount);
            const cardHtml =
                '<div class="layui-col-xs2">' +
                    '<div class="layui-row card">' +
                        '<div class="layui-col-xs8">' +
                            '<div class="card-title">' + card.title + '</div>' +
                            '<div class="card-num"><span class="card-number">' + card.number + '</span><span>&emsp;笔</span></div>' +
                            '<div class="card-amt"><span class="card-amount">￥' + formattedAmount + '</span></div>' +
                        '</div>' +
                        '<div class="layui-col-xs4 card-icon">' +
                            '<svg class="icon" aria-hidden="true">' +
                                '<use xlink:href="' + card.icon + '"></use>' +
                            '</svg>' +
                        '</div>' +
                    '</div>' +
                '</div>';
            summaryBoard.append(cardHtml);
        });
    }

    // 渲染明细统计看板
    function renderDetailsBoard(details) {
        const detailsBoard = $('#details-board');
        detailsBoard.empty();

        // 创建一个映射来存储返回的数据
        const detailMap = {};
        if (details && details.length > 0) {
            details.forEach(function(detail) {
                detailMap[detail.type] = detail;
            });
        }

        // 为所有类型渲染数据，没有的显示0
        ALL_PAYMENT_TYPES.forEach(function(type, index) {
            const isLast = index === ALL_PAYMENT_TYPES.length - 1;
            const borderClass = isLast ? '' : 'style="border-right: 1px dashed #004788;padding-left: 5px;padding-right: 5px;"';

            // 获取该类型的数据，没有则使用默认值
            const detail = detailMap[type] || { type: type, count: 0, amount: 0 };
            const formattedAmount = formatNumber(detail.amount);

            const detailHtml =
                '<div class="layui-col-seventh" ' + borderClass + '>' +
                    '<div class="detail-title">' + detail.type + '</div>' +
                    '<div class="detail-content">' +
                        '<div class="detail-combined">' + detail.count + 'ㅤㅤ￥' + formattedAmount + '</div>' +
                    '</div>' +
                '</div>';
            detailsBoard.append(detailHtml);
        });
    }

    // 初始化图表
    function initCharts(trendData) {
        var chartDom = document.getElementById('chart');
        var myChart = echarts.init(chartDom);

        // 处理趋势数据
        if (!trendData || trendData.length === 0) {
            chartDom.innerHTML = '<div style="text-align: center; color: #999; padding: 200px 0;">暂无数据</div>';
            return;
        }

        const trend = trendData[0];
        const dates = getLast30Days();

        // 生成x轴标签（只显示日）
        const xAxisLabels = dates.map(function(date) {
            return new Date(date).getDate(); // 获取日期部分
        });

        // 初始化数据结构
        const seriesData = {
            '一般支付申请_count': Array(30).fill(0),
            '财政支付申请_count': Array(30).fill(0),
            '政府采购申请无指标_count': Array(30).fill(0),
            '零星采购申请_count': Array(30).fill(0),
            '公务卡申请_count': Array(30).fill(0),
            '支付申请_count': Array(30).fill(0),
            '教育收费申请_count': Array(30).fill(0),
            '一般支付申请_amount': Array(30).fill(0),
            '财政支付申请_amount': Array(30).fill(0),
            '政府采购申请无指标_amount': Array(30).fill(0),
            '零星采购申请_amount': Array(30).fill(0),
            '公务卡申请_amount': Array(30).fill(0),
            '支付申请_amount': Array(30).fill(0),
            '教育收费申请_amount': Array(30).fill(0)
        };


        // 填充实际数据
        if (trend.data) {
            // 创建日期到索引的映射
            const dateIndexMap = {};
            dates.forEach(function(date, index) {
                dateIndexMap[date] = index;
            });

            // 遍历接口返回的数据
            Object.keys(trend.data).forEach(function(dateStr) {
                // 查找该日期在30天数组中的索引
                const index = dateIndexMap[dateStr];
                if (index !== undefined && trend.data[dateStr]) {
                    // 遍历该日期的所有数据项
                    Object.keys(trend.data[dateStr]).forEach(function(key) {
                        if (seriesData.hasOwnProperty(key)) {
                            seriesData[key][index] = trend.data[dateStr][key] || 0;
                        }
                    });
                }
            });
        }

        // 计算总支付金额
        const totalAmountData = seriesData['一般支付申请_amount'].map(function(val, index) {
            return val +
                seriesData['财政支付申请_amount'][index] +
                seriesData['政府采购申请无指标_amount'][index] +
                seriesData['零星采购申请_amount'][index] +
                seriesData['公务卡申请_amount'][index] +
                seriesData['支付申请_amount'][index] +
                seriesData['教育收费申请_amount'][index];
        });

        // 构造图表配置
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            toolbox: {
                feature: {
                    dataView: { show: true, readOnly: false, title: '数据视图' },
                    magicType: { show: true, type: ['line', 'bar'], title: {
                            line: '折线图',
                            bar: '柱状图'
                        } },
                    restore: { show: true, title: '还原' },
                    saveAsImage: { show: true, title: '保存为图片' }
                }
            },
            legend: {
                show: true,
                data: ['一般支付申请', '财政支付申请', '政府采购申请无指标', '零星采购申请', '公务卡申请', '支付申请', '教育收费申请', '总支付金额']
            },
            xAxis: [
                {
                    name: '日期',
                    type: 'category',
                    data: xAxisLabels,
                    axisPointer: {
                        type: 'shadow'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '支付数量',
                    axisLabel: {
                        formatter: '{value} 笔'
                    }
                },
                {
                    type: 'value',
                    name: '支付金额(元)',
                    axisLabel: {
                        formatter: '￥{value}'
                    }
                }
            ],
            series: [
                {
                    name: '一般支付申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['一般支付申请_count'],
                    itemStyle: {
                        color: '#F8CDBE'
                    }
                },
                {
                    name: '财政支付申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['财政支付申请_count'],
                    itemStyle: {
                        color: '#F0A599'
                    }
                },
                {
                    name: '政府采购申请无指标',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['政府采购申请无指标_count'],
                    itemStyle: {
                        color: '#A6DDEA'
                    }
                },
                {
                    name: '零星采购申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['零星采购申请_count'],
                    itemStyle: {
                        color: '#80CFC4'
                    }
                },
                {
                    name: '公务卡申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['公务卡申请_count'],
                    itemStyle: {
                        color: '#9EA9C3'
                    }
                },
                {
                    name: '支付申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['支付申请_count'],
                    itemStyle: {
                        color: '#659BBD'
                    }
                },
                {
                    name: '教育收费申请',
                    type: 'bar',
                    stack: 'Ad',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + ' 笔';
                        }
                    },
                    data: seriesData['教育收费申请_count'],
                    itemStyle: {
                        color: '#BEB9DA'
                    }
                },
                {
                    name: '总支付金额',
                    type: 'line',
                    yAxisIndex: 1,
                    tooltip: {
                        valueFormatter: function (value) {
                            return '￥' + formatNumber(value);
                        }
                    },
                    data: totalAmountData,
                    itemStyle: {
                        color: '#BC5F4E'
                    }
                }
            ]
        };

        option && myChart.setOption(option);
    }

    // 获取最近30天日期
    function getLast30Days() {
        const dates = [];
        const today = new Date();

        for (let i = 29; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(today.getDate() - i);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date.getDate().toString().padStart(2, "0");
            dates.push(year + "-" + month + "-" + day);
        }

        return dates;
    }

    // 格式化数字
    function formatNumber(num) {
        if (num === undefined || num === null || isNaN(num)) return '0.00';
        return parseFloat(num).toLocaleString('zh-CN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    // 支付单类型多选处理
    $(document).ready(function() {
        // 使用layui的form模块渲染复选框
        layui.use('form', function() {
            var form = layui.form;
            form.render('checkbox');

            // 延迟绑定事件，确保DOM元素已经渲染完成
            setTimeout(function() {
                // 点击显示/隐藏下拉选项
                $('#zfdjlxShow').on('click', function(e) {
                    e.stopPropagation();
                    $('#zfdjlxContent').toggle();
                });

                // 复选框变更事件 - 使用layui的事件监听
                form.on('checkbox', function(data) {
                    updateZfdjlxDisplay();
                });
            }, 100);
        });

        // 点击页面其他地方隐藏下拉选项
        $(document).on('click', function(e) {
            if (!$(e.target).closest('#zfdjlxShow').length &&
                !$(e.target).closest('#zfdjlxContent').length) {
                $('#zfdjlxContent').hide();
            }
        });

        // 阻止点击选项区域时隐藏
        $('#zfdjlxContent').on('click', function(e) {
            e.stopPropagation();
        });

        // 更新显示文本
        function updateZfdjlxDisplay() {
            var selectedCount = $('input[name="zfdjlxOptions"]:checked').length;

            var displayText;
            if (selectedCount === 0) {
                displayText = '全部';
            } else {
                displayText = '已选择' + selectedCount + '项';
            }

            $('#zfdjlxText').text(displayText);

            // 更新隐藏字段
            var selectedValues = [];
            $('input[name="zfdjlxOptions"]:checked').each(function() {
                selectedValues.push($(this).val());
            });
            $('#zfdjlx').val(selectedValues.join(','));
        }

        // 初始化显示
        updateZfdjlxDisplay();
    });

    function search() {
        let data = form.val("searchForm");
        table.render({
            method: 'post',
            elem: '#dataTable',
            url: '<%=path%>/api/pageList',
            where: data,
            cellMinWidth: 80,
            loading: true,
            page: true,
            totalRow: true,
            size: 'sm',
            limit: 20,
            limits: [10, 20, 30, 50, 100],
            cols: [[
                {type: 'numbers', width: '4%', minWidth: 30, title: '序号', fixed: 'left'},
                {field: 'id', hide: true, fixed: 'left'},
                {field: 'zfdjlx', width: '8%', minWidth: 100, title: '支付单类型', align: 'center', templet: '#codeTemplate', fixed: 'left'},
                {field: 'zfzt', width: '7%', minWidth: 100, title: '支付单状态', align: 'center', templet: '#zfztTemplate', fixed: 'left'},
                {field: 'zfje', width: '8%', minWidth: 100, title: '支付金额', align: 'right', fixed: 'left', templet: '#zfjeTemplate'},
                {field: 'zdsj', width: '8%', minWidth: 100, title: '制单时间', align: 'center', fixed: 'left'},
                {field: 'djbh', width: '8%', minWidth: 100, title: '原始单据编号', align: 'center', fixed: 'left'},
                {field: 'skr', width: '8%', minWidth: 100, title: '收款人', align: 'center'},
                {field: 'yhzh', width: '10%', minWidth: 100, title: '银行账号', align: 'center', templet: '#yhzhTemplate'},
                {field: 'djlxmc', width: '10%', minWidth: 100, title: 'U8单据类型', align: 'center'},
                {field: 'xmdm', width: '10%', minWidth: 100, title: 'U8项目', align: 'center', templet: '#xmdmTemplate'},
                {field: 'zbzy', width: '10%', minWidth: 100, title: 'U8指标', align: 'center', templet: '#zbzyTemplate'},
                {field: 'ysxmdm', width: '10%', minWidth: 100, title: 'U8预算项目', align: 'center', templet: '#ysxmdmTemplate'},
                {field: 'zjxzdm', width: '10%', minWidth: 100, title: 'U8资金性质', align: 'center', templet: '#zjxzdmTemplate'},
                {field: 'whdm', width: '10%', minWidth: 100, title: 'U8指标文号', align: 'center', templet: '#whdmTemplate'},
                {field: 'sfzfcg', width: '8%', minWidth: 100, title: '是否政府采购', align: 'center', templet: '#sfzfcgTemplate'},
                {field: 'zfbmjjl', width: '10%', minWidth: 100, title: '财政部门经济分类', align: 'center'},
                {field: 'zfzfjjfl', width: '10%', minWidth: 100, title: '财政政府经济分类', align: 'center'},
                {field: 'zfzcgnfl', width: '10%', minWidth: 100, title: '财政支出功能分类', align: 'center'},
                {field: 'zfzjxz', width: '10%', minWidth: 100, title: '财政资金性质', align: 'center'},
                {field: 'zfzblx', width: '10%', minWidth: 100, title: '财政指标类型', align: 'center'},
                {field: 'zfxm', width: '10%', minWidth: 100, title: '财政预算项目', align: 'center'},
                {field: 'zfzbwh', width: '10%', minWidth: 100, title: '财政指标文号', align: 'center'},
                {field: 'zfztbzxx', width: '10%', minWidth: 100, title: '制单状态备注', align: 'center'},
                {field: 'doubt', width: '8%', minWidth: 100, title: '是否存疑', align: 'center', templet: '#doubtTemplate'},
                {field: 'doubtzy', width: '10%', minWidth: 100, title: '存疑摘要', align: 'left'},
                {field: 'auditor', width: '8%', minWidth: 100, title: '审核人', align: 'center'}
            ]],
            done: function (res) {
                // 显示合计行
                if (res.other && res.other.totalZfje !== undefined) {
                    let $totalRow = $('.layui-table-total');
                    if ($totalRow.length > 0) {
                        // 在支付单类型列显示"合计"
                        let $zfdjlxCell = $totalRow.find('td[data-field="zfdjlx"] .layui-table-cell');
                        if ($zfdjlxCell.length > 0) {
                            $zfdjlxCell.html('合计');
                        }

                        // 在支付金额列只显示金额
                        let $zfjeCell = $totalRow.find('td[data-field="zfje"] .layui-table-cell');
                        if ($zfjeCell.length > 0) {
                            $zfjeCell.html(parseFloat(res.other.totalZfje).toLocaleString('zh-CN', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2
                            }));
                        }
                    }
                }

                // 在分页条后面加"导出全部"按钮
                let $page = $('.layui-table-page');
                if ($page.find('.export-all-btn').length === 0) {
                    $page.append(
                        '<button class="layui-btn layui-btn-sm export-all-btn" style="margin-left:10px; background-color: #1E90FF !important;">' +
                        '<i class="layui-icon layui-icon-download-circle" style="font-size:14px;margin-right:3px;"></i>导出' +
                        '</button>'
                    );
                }
            }
        });
    }

    // 导出全部
    $(document).on('click', '.export-all-btn', function () {
        let data = form.val("searchForm");
        let url = '<%=path%>/api/exportAll?' + $.param(data);

        // 用 iframe 下载，不刷新页面
        let $iframe = $('#downloadFrame');
        if ($iframe.length === 0) {
            $iframe = $('<iframe id="downloadFrame" style="display:none"></iframe>');
            $('body').append($iframe);
        }
        $iframe.attr('src', url);

        layer.msg('正在导出，请稍候...', {time: 1500});
    });

    function resetForm() {
        // 清空所有输入框
        $('#searchForm input[type="text"]').val('');

        // 重置所有下拉选择框
        $('#searchForm select').val('');

        // 重置支付单类型多选框
        $('#zfdjlxOptions input[type="checkbox"]').prop('checked', false);
        $('#zfdjlx').val('');
        $('#zfdjlxText').text('全部');

        // 重新渲染表单
        form.render();

        // 重新执行查询
        search();
    }


    function view(id) {
        layer.open({
            title: "单据明细",
            type: 2,
            anim: -1,
            isOutAnim: false,
            content: "<%=path%>/api/detailPage.html?id=" + id,
            area: ["99%", "99%"],
            shade: 0.6,
            shadeClose: false,
            success: function (layero, index) {
                let frameWindow = layero.find('iframe')[0].contentWindow;
                frameWindow._parentLayerWindow = window;
            }
        });
    }

    function exit_() {
        layer.confirm('确认退出吗?', function (index) {
            $.ajax({
                type: 'get',
                url: '<%=path%>/login/exit',
                success: function(rs) {
                    if (rs.code == 200) {
                        window.location.href = '<%=path%>/login/login.html';
                    }
                }
            })
            layer.close(index);
        });
    }

</script>
<script type="text/html" id="codeTemplate">
    <a href="javascript:view('{{d.id}}')" style="color: #004788;font-weight: bolder;text-decoration: underline;">{{d.zfdjlx}}</a>
</script>
<script type="text/html" id="zfztTemplate">
    {{#  if(d.zfzt == 0){ }}
    <a class="layui-btn layui-btn-normal layui-btn-xs" style="background-color: #FFB800 !important;">&emsp;待制单&emsp;</a>
    {{#  } else  if(d.zfzt == 1){ }}
    <a class="layui-btn layui-btn-success layui-btn-xs">&emsp;制单成功&emsp;</a>
    {{#  } else  if(d.zfzt == 2){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs">&emsp;制单失败&emsp;</a>
    {{#  } }}
</script>
<script type="text/html" id="xmdmTemplate">
    {{d.xmdm + '-' + d.xmmc}}
</script>
<script type="text/html" id="zbzyTemplate">
    {{d.zbid + '-' + d.zbzy}}
</script>
<script type="text/html" id="ysxmdmTemplate">
    {{d.ysxmdm + '-' + d.ysxmmc}}
</script>
<script type="text/html" id="zjxzdmTemplate">
    {{d.zjxzdm + '-' + d.zjxzmc}}
</script>
<script type="text/html" id="whdmTemplate">
    {{d.whdm + '-' + d.whmc}}
</script>
<script type="text/html" id="sfzfcgTemplate">
    {{#  if(d.zfzt == 0){ }}
    <a class="layui-btn layui-btn-normal layui-btn-xs">&emsp;否&emsp;</a>
    {{#  } else  if(d.zfzt == 1){ }}
    <a class="layui-btn layui-btn-succ layui-btn-xs">&emsp;是&emsp;</a>
    {{#  } }}
</script>
<script type="text/html" id="doubtTemplate">
    {{#  if(d.doubt == 1){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs">&emsp;是&emsp;</a>
    {{#  } else { }}
    <a class="layui-btn layui-btn-succ layui-btn-xs">&emsp;否&emsp;</a>
    {{#  } }}
</script>
<script type="text/html" id="zfjeTemplate"> {{#
    return parseFloat(d.zfje).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
        });
    }}
</script>
<script type="text/html" id="yhzhTemplate"> {{#
        var showValue = '';
<%--        // 公务卡申请类型优先显示公务卡号--%>
        if(d.zfdjlx === '公务卡申请') {
            showValue = d.gwkh || d.yhzh || '';
        } else {
<%--        // 其他类型优先显示银行账号--%>
            showValue = d.yhzh || d.gwkh || '';
        }
        return showValue;
    }}
</script>

</body>
</html>
